package com.yuan.mint.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.LocationManager;
import android.util.Log;

import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.yuan.mint.R;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class MintUtils {

    /**
     * 判断是否是第一次
     */
    public static final String APP_VERSIONCODE_KEY = "versionCode";
    public static final String APP_ISFIRST_KEY = "isFirst";
    public static final String APP_SP_ISFIRST = "first";

    /**
     * 全局图片加载配置
     */
    public static final String APP_IMAGE_CACHE = "imageCache";

    public static String downloadJSON(String path) {
        String str = "";
        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            int status = conn.getResponseCode();
            if (status == HttpURLConnection.HTTP_OK) {
                BufferedReader br = new BufferedReader(new InputStreamReader(
                        conn.getInputStream()));
                String temp = "";
                while ((temp = br.readLine()) != null) {
                    str += temp;
                }
                br.close();
                conn.disconnect();
            } else {
                Log.e("HttpUtils", "网络错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }

    public static Bitmap downloadImage(String path) {
        Bitmap bitmap = null;
        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            int status = conn.getResponseCode();
            if (status == HttpURLConnection.HTTP_OK) {
                bitmap = BitmapFactory.decodeStream(conn.getInputStream());
                conn.disconnect();
            } else {
                Log.e("HttpUtils", "网络错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    /**
     * 判断是否是第一次运行
     */
    public static boolean isFirst(Context context) {
        int versionCode;
        boolean first;
        SharedPreferences sp = context.getSharedPreferences(APP_SP_ISFIRST, Context.MODE_PRIVATE);
        first = sp.getBoolean(APP_ISFIRST_KEY, true);
        versionCode = sp.getInt(APP_VERSIONCODE_KEY, 1);
        if (getVersion(context) != versionCode || first) {
            sp.edit().putBoolean(APP_ISFIRST_KEY, false).commit();
            sp.edit().putInt(APP_VERSIONCODE_KEY, getVersion(context)).commit();
        }
        return first;
    }

    /**
     * 获得程序版本号
     */
    public static int getVersion(Context context) {
        int versionCode = 1;
        PackageManager pm = context.getPackageManager();
        try {
            PackageInfo info = pm.getPackageInfo(context.getPackageName(), 0);
            versionCode = info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    /**
     * 获取程序APP根目录
     */
    public static String getRootCache(Context context) {
        File externalCacheDir = context.getExternalCacheDir();
        if (externalCacheDir != null && !externalCacheDir.exists()) {
            externalCacheDir.mkdirs();
        }
        return externalCacheDir != null ? externalCacheDir.getAbsolutePath() : null;
    }

    /**
     * 获取图片的保存路径
     */
    public static File getImageCache(Context context) {
        String imageCache = getRootCache(context) + File.separator + APP_IMAGE_CACHE;
        File file = new File(imageCache);
        if (!file.exists()) {
            file.mkdir();
        }
        return file;
    }

    /**
     * UIL  University Image Loader全局配置图片加载框架
     */
    public static void configGlobalImageLoader(Context context) {
        ImageLoaderConfiguration.Builder builder = new ImageLoaderConfiguration.Builder(context);
        builder.diskCache(new UnlimitedDiskCache(getImageCache(context)));
        ImageLoader.getInstance().init(builder.build());
    }

    /**
     * UIL 设置图片初始化
     */
    public static DisplayImageOptions getDisplayImageLoader() {
        DisplayImageOptions.Builder builder = new DisplayImageOptions.Builder();
        builder.showImageOnFail(R.mipmap.ic_launcher);
        builder.showImageOnLoading(R.mipmap.ic_launcher);
        builder.cacheInMemory(true);
        builder.cacheOnDisk(true);
        return builder.build();
    }

    /**
     * 判断GPS是否开启，GPS或者AGPS开启一个就认为是开启的
     * @param context
     * @return true 表示开启
     */
    public static boolean isOPen(Context context) {
        LocationManager locationManager
                = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        // 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        // 通过WLAN或移动网络(3G/2G)确定的位置（也称作AGPS，辅助GPS定位。主要用于在室内或遮盖物（建筑群或茂密的深林等）密集的地方定位）
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || network) {
            return true;
        }

        return false;
    }
}
